from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from . import db, login_manager
from datetime import datetime

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    role = db.Column(db.String(20), nullable=False, default='researcher')
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>'

# 用户加载函数
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class Sample(db.Model):
    __tablename__ = 'samples'
    
    id = db.Column(db.Integer, primary_key=True)
    sample_id = db.Column(db.String(50), unique=True, nullable=False)
    variety_name = db.Column(db.String(100), nullable=False)
    collection_date = db.Column(db.Date, nullable=False)
    location = db.Column(db.String(200), nullable=False)
    hardness = db.Column(db.Float)
    protein_content = db.Column(db.Float)
    moisture_content = db.Column(db.Float)
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # 关联用户
    user = db.relationship('User', backref=db.backref('samples', lazy=True))

    def __repr__(self):
        return f'<Sample {self.sample_id}>'

class MarkerAnalysis(db.Model):
    __tablename__ = 'marker_analyses'
    
    id = db.Column(db.Integer, primary_key=True)
    sample_id = db.Column(db.Integer, db.ForeignKey('samples.id'), nullable=False)
    pina_type = db.Column(db.String(20))  # Pina基因类型
    pinb_type = db.Column(db.String(20))  # Pinb基因类型
    grain_hardness = db.Column(db.String(20))  # 籽粒硬度分类
    sequence_data = db.Column(db.Text)  # 序列数据
    analysis_date = db.Column(db.DateTime, default=datetime.utcnow)
    notes = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # 关联
    sample = db.relationship('Sample', backref=db.backref('marker_analyses', lazy=True))
    user = db.relationship('User', backref=db.backref('marker_analyses', lazy=True))

    def __repr__(self):
        return f'<MarkerAnalysis {self.id}>'
